package com.qiu.greened.adapter

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.INgvImageLoader
import com.lwkandroid.widget.ngv.NgvChildImageView
import com.lwkandroid.widget.ngv.NineGridView
import com.qiu.greened.R
import com.qiu.greened.bean.PostBean
import com.qiu.greened.bean.StarBean
import com.qiu.greened.network.PostService
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.ui.my.LoginActivity
import com.qiu.greened.ui.post.PostInfoActivity
import com.qiu.greened.ui.post.PostUserActivity
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.getTimeFormatText
import com.qiu.greened.utils.showToast
import com.sackcentury.shinebuttonlib.ShineButton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 继承自 PagingDataAdapter
 * COMPARATOR: Paging 3 在内部使用 DiffUtil 来管理数据变化
 */
class PostAdapter : PagingDataAdapter<PostBean, PostAdapter.ViewHolder>(COMPARATOR) {
    object COMPARATOR : DiffUtil.ItemCallback<PostBean>() {
        override fun areItemsTheSame(oldItem: PostBean, newItem: PostBean): Boolean {
            return oldItem.postId == newItem.postId
        }

        override fun areContentsTheSame(oldItem: PostBean, newItem: PostBean): Boolean {
            return oldItem == newItem
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imgUser: ImageView = view.findViewById(R.id.img_user)
        val textName: TextView = view.findViewById(R.id.text_name)
        val textContext: TextView = view.findViewById(R.id.text_content)
        val gridView: NineGridView = view.findViewById(R.id.grid_view)
        val textStar: TextView = view.findViewById(R.id.text_star)
        val textReply: TextView = view.findViewById(R.id.text_reply)
        val textTime: TextView = view.findViewById(R.id.text_time)
        val btnStar: ShineButton = view.findViewById(R.id.btn_send)
        val btnReply: ImageView = view.findViewById(R.id.btn_reply)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_post_list, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: PostAdapter.ViewHolder, position: Int) {
        val item = getItem(position)
        if (item != null) {
            //赋值
            holder.textName.text = item.nickName
            holder.textContext.text = item.postContent
            holder.textStar.text = item.postStar.toString()
            holder.textReply.text = item.postReply.toString()
            holder.textTime.text = getTimeFormatText(item.createTime)
            Glide.with(holder.itemView.context).load(ServiceCreator.BASE_URL + item.userAvatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop())).into(holder.imgUser)
            holder.btnStar.isChecked = item.isStar
            //点击事件
            holder.itemView.setOnClickListener {
                val intent = Intent(holder.itemView.context, PostInfoActivity::class.java)
                intent.putExtra("postId", item.postId)
                holder.itemView.context.startActivity(intent)

            }
            //头像
            holder.imgUser.setOnClickListener {
                val intent = Intent(holder.itemView.context, PostUserActivity::class.java)
                intent.putExtra("userId", item.userId)
                holder.itemView.context.startActivity(intent)

            }
            //点赞
            holder.btnStar.setOnClickListener {
                CoroutineScope(Dispatchers.Main).launch {
                    try {
                        val data = ServiceCreator.create<PostService>()
                            .setStar(MyData.token, StarBean(MyData.userId, item.postId))
                        holder.textStar.text = when (data.msg) {
                            "insert" -> (holder.textStar.text.toString().toInt() + 1).toString()
                            "delete" -> (holder.textStar.text.toString().toInt() - 1).toString()
                            else -> holder.textStar.text.toString()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        "${e.message}".showToast()
                        Log.i("请求失败", "${e.message}")
                    }
                }
            }
            if (item.postImg != null && item.postImg != "") {
                //创建图片加载器
                class GlideDisplay : INgvImageLoader<String> {
                    override fun load(url: String, imageView: ImageView, width: Int, height: Int) {
                        Glide.with(imageView.context)
                            .load(ServiceCreator.BASE_URL + url)
                            .apply(RequestOptions().override(width, height).transform(CenterCrop(), RoundedCorners(10)))
                            .into(imageView)
                    }
                }
                //NineGridView的数据适配器，构造方法中必须设置最大数据容量和图片加载器
                val ngvAdapter = DefaultNgvAdapter(3, GlideDisplay())
                ngvAdapter.setOnChildClickListener(object :
                    DefaultNgvAdapter.OnChildClickedListener<String> {
                    override fun onContentImageClicked(
                        position: Int, data: String, childImageView: NgvChildImageView?
                    ) {
                        Log.d("image", data)
                        //点击图片时的回调
                    }
                    override fun onPlusImageClicked(plusImageView: ImageView, dValueToLimited: Int) {}
                    override fun onImageDeleted(position: Int, data: String) {}
                })
                holder.gridView.adapter = ngvAdapter
                val serList = item.postImg.split("&").take(3)
                ngvAdapter.addDataList(serList)
            }
        }
    }
}